<?php
class WeeklyBonus extends AppModel {
    var $useDbConfig  = 'mssql';
    var $useTable     = 'WeeklyBonus';
    var $primaryKey   = 'WeeklyBonusID';
    var $displayField = 'BonusDate';
    var $name         = 'WeeklyBonus';
    var $belongsTo = array(
        'Membership' => array(
            'className'  => 'Membership',
            'foreignKey' => 'MembershipID'
        )
    );

    public function getCurrentBvInfo ($ids) {
        $data = $this->find('all', array(
            'conditions' => array(
                'MembershipID' => $ids
            ),
            'recursive'  => -1,
            'fields'     => array('MembershipID', 'PBV', 'MBV', 'bfMBV', 'APBV', 'cyclecount', 'MTDPPV', 'GPB1', 'GPB2', 'GPB3')
        ));
        $resp = array();

        if (count($data) == 0) {
            return 0;
        }


        foreach ($data as $m) {
            $id  = $m['WeeklyBonus']['MembershipID'];
            $bf  = $m['WeeklyBonus']['bfMBV'];
            $pbv = $m['WeeklyBonus']['MTDPPV'];
            $mbv = $m['WeeklyBonus']['MBV'];
            $cyc = $m['WeeklyBonus']['cyclecount'];

            if ($m['WeeklyBonus']['MBV'] > 110) { // current month maintenance BV already above 110
                $bf = $mbv;
            } else if ($bf < 110) {
                $bf += $mbv;
                $bf  = ($bf > 110) ? 110 : $bf; // maximum brought forward maintenance BV = 110
            }

            $rbv = $bf - $pbv;
            $obv = ($rbv >= 0) ? 0 : '+'.abs($rbv); // BV that have over commit in this month
            $rbv = ($rbv < 0) ? 0 : $rbv; // BV need to Buy by the end of this month
            $rdb = ($rbv == 0) ? '<span class="green">Yes</span>' : '<span class="red">No</span>';

            $resp[$id] = array(
                'pbv'  => $pbv.' BV',
                'mbv'  => $mbv.' BV',
                'rbv'  => $rbv.' BV',
                'obv'  => $obv.' BV',
                'apbv' => $m['WeeklyBonus']['APBV'].' BV',
                'AC'   => 0,
                'CC'   => $m['WeeklyBonus']['PBV'],
                'BC'   => 0,
                'BP1'  => $m['WeeklyBonus']['GPB1'],
                'BP2'  => $m['WeeklyBonus']['GPB2'],
                'BP3'  => $m['WeeklyBonus']['GPB3'],
                'RDB'  => $rdb
            );

            if ($cyc > 0) {
                $cyc = $cyc / 4;

                if ($cyc > 20) {
                    $unit = $cyc - 20;
                    $cyc -= $unit;
                    $resp[$id]['BU3'] = $unit;
                    $resp[$id]['BB3'] = $unit * 220;
                }
                if ($cyc > 10) {
                    $unit = $cyc - 10;
                    $cyc -= $unit;
                    $resp[$id]['BU2'] = $unit - 10;
                    $resp[$id]['BB2'] = $unit * 220;
                }
                if ($cyc > 0) {
                    $resp[$id]['BU1'] = $cyc;
                    $resp[$id]['BB1'] = $cyc * 220;
                }
            }
        }

        $cnt  = count($ids);
        $sql  = 'SELECT TOP '.$cnt.' [m].[MembershipID], [b].[GBV] FROM [WeeklyBonus] AS [b] ' .
                'INNER JOIN [Memberships] AS [m] ' .
                'ON ([b].[MembershipID]=[m].[leftid]) ' .
                'WHERE [m].[MembershipID] IN ('.implode(',', $ids).') ' .
                'ORDER BY [b].[WeeklyBonusID] DESC';
        $data = $this->query($sql);
        $temp = array();

        if (count($data) > 0) {
            foreach ($data as $b) {
                $id = $b[0]['MembershipID'];

                if (!in_array($id, $temp)) {
                    $temp[]          = $id;
                    $resp[$id]['AC'] = $b[0]['GBV'];
                }
            }
        }

        $sql  = 'SELECT TOP '.$cnt.' [m].[MembershipID], [b].[GBV] FROM [WeeklyBonus] AS [b] ' .
                'INNER JOIN [Memberships] AS [m] ' .
                'ON ([b].[MembershipID]=[m].[rightid]) ' .
                'WHERE [m].[MembershipID] IN ('.implode(',', $ids).') ' .
                'ORDER BY [b].[WeeklyBonusID] DESC';
        $data = $this->query($sql);
        $temp = array();

        if (count($data) > 0) {
            foreach ($data as $b) {
                $id = $b[0]['MembershipID'];

                if (!in_array($id, $temp)) {
                    $temp[]          = $id;
                    $resp[$id]['BC'] = $b[0]['GBV'];
                }
            }
        }

        return $resp;
    } // getCurrentBvInfo

    public function bvStatus ($data) {
        set_time_limit(0);

        $legs = array('A', 'B');

        foreach ($legs as $l) {
            if (isset($data[$l]) && count($data[$l]) > 0) {
                foreach ($data[$l] as $i=>$m) {
                    $mm = $this->find('first', array(
                        'conditions' => array(
                            'MembershipID' => $m['mem_id']
                        ),
                        'recursive'  => -1,
                        'fields'     => array('PBV', 'MBV', 'bfMBV')
                    ));

                    $pbv = $mm['WeeklyBonus']['PBV'];
                    $mbv = $mm['WeeklyBonus']['MBV'];
                    $bf  = $mm['WeeklyBonus']['bfMBV'];

                    if ($mbv > 110) { // current month maintenance BV already above 110
                        $bf = $mbv;
                    } else if ($bf < 110) {
                        $bf += $mbv;
                        $bf  = ($bf > 110) ? 110 : $bf; // maximum brought forward maintenance BV = 110
                    }

                    $rbv = $bf - $pbv;
                    $rbv = ($rbv < 0) ? 0 : $rbv; // BV need to Buy by the end of this month
                    $rdb = ($rbv == 0) ? '<span class="green">Yes</span>' : '<span class="red">No</span>';

                    $data[$l][$i]['pbv'] = $pbv;
                    $data[$l][$i]['rbv'] = $rbv;
                    $data[$l][$i]['rdb'] = $rdb;
                }
            }
        }

        return $data;
    } // bvStatus

    public function bvInfo ($data) {
        set_time_limit(0);

        if (isset($data) && count($data) > 0) {
            foreach ($data as $i=>$m) {
                $mm = $this->find('first', array(
                    'conditions' => array(
                        'MembershipID' => $m['mem_id']
                    ),
                    'recursive'  => -1,
                    'fields'     => array('PBV', 'MBV', 'bfMBV', 'APBV')
                ));

                $mbv = $mm['WeeklyBonus']['MBV'];
                $bf  = $mm['WeeklyBonus']['bfMBV'];

                if ($mbv > 110) { // current month maintenance BV already above 110
                    $bf = $mbv;
                } else if ($bf < 110) {
                    $bf += $mbv;
                    $bf  = ($bf > 110) ? 110 : $bf; // maximum brought forward maintenance BV = 110
                }

                $rbv = $bf - $mm['WeeklyBonus']['PBV'];
                $rbv = ($rbv <= 0) ? 0 : '<span class="red">'.$rbv.'</span>'; // BV need to Buy by the end of this month
                $rdb = ($rbv !== 0) ? '<span class="red">No</span>' : '<span class="green">Yes</span>';

                $data[$i]['pbv'] = ($mm['WeeklyBonus']['APBV']) ? $mm['WeeklyBonus']['APBV'] : '0';
                $data[$i]['rbv'] = $rbv;
                $data[$i]['rdb'] = $rdb;
            }
        }

        return $data;
    } // bvInfo

    public function bonusList ($params, $id) {
        $page = $params['page'];

        if ($params['query'] && $params['qtype']) {
            $cond = array('WeeklyBonus.'.$params['qtype'].' LIKE' => '%'.$params['query'].'%');
        }
        $cond['WeeklyBonus.MembershipID'] = $id;

        $total = $this->find('count', array('conditions' => $cond));

        if ($total == 0) {
            return 0;
        }

        $sort = empty($params['sortname']) ? 'WeeklyBonusID' : $params['sortname'];
        $ord  = (empty($params['sortorder']) || $params['sortorder'] == 'asc') ? 'ASC' : 'DESC';
        $rpp  = isset($params['rp']) ? $params['rp'] : 10;

        $data = $this->find('all', array(
            'conditions' => $cond,
            'recursive'  => -1,
            'order'      => array('WeeklyBonus.'.$sort.' '.$ord),
            'limit'      => $rpp,
            'page'       => $page
        ));

        $rec = array();

        if (count($data) == 0) {
            return 0;
        }

        foreach ($data as $rs) {
            $id = $rs['WeeklyBonus']['WeeklyBonusID'];

            $actions   = '<div title="'.__('Details',true).'" class="report"></div><div class="clear" style="height:0; padding:0;"></div>';
            $startDate = $this->serverToClientTime($rs['WeeklyBonus']['BonusDate'], 'd/m/Y');
            $endDate   = $this->serverToClientTime($rs['WeeklyBonus']['BonusDate'], 'd/m/Y H:i');
            $payDate   = $this->serverToClientTime($rs['WeeklyBonus']['BonusDate'], 'd/m/Y');
            $cycle     = ($rs['WeeklyBonus']['cyclecount'] / 4) * 100;
            $coupon    = $rs['WeeklyBonus']['Coupons'] * 100;
            $bf        = $rs['WeeklyBonus']['bfMBV'];

            if ($rs['WeeklyBonus']['MBV'] > 110) { // current month maintenance BV already above 110
                $bf = $rs['WeeklyBonus']['MBV'];
            } else if ($bf < 110) {
                $bf += $rs['WeeklyBonus']['MBV'];
                $bf  = ($bf > 110) ? 110 : $bf; // maximum brought forward maintenance BV = 110
            }
            $overcommit = $rs['WeeklyBonus']['PBV'] - $bf;
            $overcommit = ($overcommit > 0) ? $overcommit : 0;

            $cell = array(
                $id, $startDate, $endDate, $payDate, number_format($rs['WeeklyBonus']['GBV'],2), number_format($overcommit, 2),
                number_format($rs['WeeklyBonus']['UPBV'],2), number_format($cycle,2), number_format($rs['WeeklyBonus']['GlobalBns'],2),
                number_format($coupon,2), number_format($rs['WeeklyBonus']['PBVDist'],2), $actions
            );

            $rec[] = array(
                'id'   => $id,
                'cell' => $cell
            );
        }

        return array(
            'page'  => $page,
            'total' => $total,
            'rows'  => $rec
        );
    } // bonusList

    public function bvAllocation ($id, $side) {
        $sql  = 'sp_ListMemberAllocationBonus "'.$id.'", "'.$side.'"';
        $data = $this->query($sql);
        $resp = array();

        if (count($data) == 0) {
            return 0;
        }

        foreach ($data as $i=>$bv) {
            $resp[$i] = array(
                'order_id'    => $bv['order_id'],
                'member_id'   => $bv['member_id'],
                'bv'          => $bv['bv'],
                'bv_alloc'    => $bv['bv_alloc'],
                'paid_date'   => $bv['paid_date'],
                'refund_date' => $bv['refund_date']
            );
        }

        return $resp;
    } // bvAllocation
} // WeeklyBonus
?>